# encoding: utf-8
from common.date_util import now_date_fmt

"""


@author: tongzhenguo


@contact: tzg@meitu.com


@time: 2019/1/24 下午4:26


@desc:
1.解析redis配置文件,通过比对ttl判断是否写入成功
2.监控redis的所有key，即将过期报警
3.免打扰时段延迟报警

"""
import redis


black_list = []
msg_list = []
time_black_range = list(range(0, 9)) + list(range(23, 24))
_redis_cache_msg_key = "bdg_msg"


def ttl_check_by_prefix_or_suffix(mhost, mport, mpassword, mdb, prefix, suffix):
    """监控redis的所有key，即将过期报警"""
    r = redis.StrictRedis(host=mhost, port=mport, db=mdb, password=mpassword)
    p = r.pipeline()
    keys = []
    for key in r.scan_iter("%s*%s" % (prefix if prefix else "", suffix if suffix else "")):
        p.ttl(key)
        keys.append(key)
    ttls = p.execute()
    for k, v in zip(keys, ttls):
        is_skip = False
        # 前缀黑名单
        for prefix_k in black_list:
            if prefix_k in k:
                is_skip = True
        if is_skip:
            continue
        if v < 3600 and k not in black_list and v != -1:  # -1是永不过期
            msg = u"%s in %s ttl %s, check plz!" % (k, mhost, v)
            if int(now_date_fmt("HH")) in time_black_range:
                if r.exists(_redis_cache_msg_key):
                    r.set(_redis_cache_msg_key, r.get(_redis_cache_msg_key) + "\n" + msg)
                else:
                    r.set(_redis_cache_msg_key, msg)
                return
            elif r.exists(_redis_cache_msg_key):
                # bdg_msg(r.get(_redis_cache_msg_key) + "\n" + msg)
                r.delete(_redis_cache_msg_key)
            else:
                # bdg_msg(msg)
                pass


# 监控特定key的生命周期
def _check_ttl(rb, conf, key, max_ttl_diff=86400):
    data_source = rb.get(conf)
    src_expire_time = int(data_source.expire_time)
    for r in data_source.redis_list:
        cur_expire_time = r.ttl(key)
        print("max is %s,current is %s,diff is %s hours" % (
            src_expire_time, cur_expire_time, (src_expire_time - cur_expire_time) / 3600))
        if not r.exists(key):
            raise RuntimeError("REDIS KEY NOT EXISTS")
        elif src_expire_time - cur_expire_time >= max_ttl_diff:
            # print( "max is %s,current is %s"  %(src_expire_time,cur_expire_time) )
            raise RuntimeError("REDIS KEY NOT UPDATE!")
        else:
            continue
    return


if __name__ == '__main__':
    pass
